package org.example.orders.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Feign;
import org.apache.commons.beanutils.BeanUtils;
import org.example.orders.config.MyPattern;
import org.example.orders.dao.OrdersDao;
import org.example.orders.entity.Orders;
import org.example.orders.entity.User;
import org.example.orders.feign.MyFeign;
import org.example.orders.service.OrdersService;
import org.example.orders.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * (Orders)表服务实现类
 *
 * @author makejava
 * @since 2025-08-06 21:29:25
 */
@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private MyFeign myFeign;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MyPattern myPattern;

    @Override
    public Orders getByIdAndUser(Serializable id) {

        /*
        * 先调自己的dao
        * 再远程调用 user的Controller方法
        * 返回一个user
        * 将user存在order里面
        * */
        Orders byId = getById(id);

/*        R byId1 = myFeign.getById(byId.getUserId());
*//*        User user = new User();
        try {
            BeanUtils.populate(user,(Map<String, ? extends Object>) byId1.getData());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }*//*
// 3. 从R里取data，强转为Map（和原来一样）
        Map<String, Object> userMap = (Map<String, Object>) byId1.getData();

// 4. 用Jackson的ObjectMapper把Map转成User对象（核心替换步骤）

        User user = objectMapper.convertValue(userMap, User.class); // 一行搞定转换
        byId.setUser(user);
        return byId;*/

        User user = myFeign.getById(byId.getUserId());
        byId.setUser(user);


        return byId;
    }







    @Override
    public Object listAndUser() {
        /*
        * 调用自己的dao
        * */

        List<Orders> list = list();
/*        list.forEach(orders -> {
            R r = myFeign.getById(orders.getUserId());
            Map<String, Object> r1 = (Map<String, Object>)r.getData();
            User user = objectMapper.convertValue(r1, User.class);
            orders.setUser(user);

        });*/

        list.forEach(orders -> {
            User user = myFeign.getById(orders.getUserId());
            orders.setUser(user);
        });
        return list;
    }

}

